﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web.Mvc;
using yiCommerce.Controllers;
using yiCommerce.Core;
using yiCommerce.Service.Orders;
using yiCommerce.Service.Payments;

namespace yiCommerce.Areas.Payment.Controllers
{
    public class PaymentAliPayController :BaseController
    {
        private IPaymentService _paymentService;

        private IWorkContext _workContext;
        private IOrderService _orderService;
        private IOrderProcessingService _orderProcessingService;

        [ValidateInput(false)]
        public ActionResult Notify(FormCollection form)
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("alipay") as AlipayPaymentMethod;
            if (processor == null )
                throw new Exception("AliPay module cannot be loaded");


            string alipayNotifyUrl = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
            string partner = _workContext.AlipayPaymethodSetting.AlipayPartner;
            if (string.IsNullOrEmpty(partner))
                throw new Exception("Partner is not set");
            string key = _workContext.AlipayPaymethodSetting.AlipayKey;
            if (string.IsNullOrEmpty(key))
                throw new Exception("Key is not set");
            string _input_charset = "utf-8";

            alipayNotifyUrl = alipayNotifyUrl + "&partner=" + partner + "&notify_id=" + Request.Form["notify_id"];
            string responseTxt = processor.Get_Http(alipayNotifyUrl, 120000);

            int i;
            NameValueCollection coll;
            coll = Request.Form;
            String[] requestarr = coll.AllKeys;
            string[] Sortedstr = processor.BubbleSort(requestarr);

            var prestr = new StringBuilder();
            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.Form[Sortedstr[i]]);
                    }
                    else
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.Form[Sortedstr[i]] + "&");

                    }
                }
            }

            prestr.Append(key);

            string mysign = processor.GetMD5(prestr.ToString(), _input_charset);

            string sign = Request.Form["sign"];

            if (mysign == sign && responseTxt == "true")
            {
                if (Request.Form["trade_status"] == "WAIT_BUYER_PAY")
                {
                    string strOrderNo = Request.Form["out_trade_no"];
                    string strPrice = Request.Form["total_fee"];
                }
                else if (Request.Form["trade_status"] == "TRADE_FINISHED" || Request.Form["trade_status"] == "TRADE_SUCCESS")
                {
                    string strTradeNo= Request.Form["out_trade_no"];

                    int tradeId= 0;
                    if (Int32.TryParse(strTradeNo, out tradeId))
                    {
                        var orders = _orderService.GetOrdersByTradeId(tradeId);
                        if (orders != null )
                        {
                            foreach (var order in orders)
                            {
                                _orderProcessingService.MarkOrderAsPaid(order.Id);
                            }
                        }
                    }
                }
                else
                {
                }

                Response.Write("success");
            }
            else
            {
                Response.Write("fail");
                string logStr = "MD5:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt;
                //_logger.Error(logStr);
            }

            return Content("");
        }

        [ValidateInput(false)]
        public ActionResult Return()
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("alipay") as AlipayPaymentMethod;
            if (processor == null)
                throw new Exception("AliPay module cannot be loaded");

            return RedirectToAction("Index", "Home", new { area = "" });
        }
    }
}